package com.wimcorp.magic.mana;

import java.util.List;
import java.util.Set;

import com.wimcorp.magic.color.Color;
import com.wimcorp.magic.exception.CostException;

public class PlayerManaPool extends ManaPool {

	public void consumeMana(ManaPool conjuredMana) throws CostException {
		Set<Color> colors =conjuredMana.getColorsInPool();
		for (Color c : colors) {
			consumeMana(getMana(c), conjuredMana.getAvailableMana(c));
		}
		

	}

	private void consumeMana(List<Mana> pool, int amount) throws CostException {
		for (int i = 0; i < amount; i++) {
			try {
				// Avoid using the same mana more then once.
				int j = i;
				while (pool.get(j).isUsed()) {
					j++;
				}
				pool.get(j).setUsed(true);
			} catch (IndexOutOfBoundsException e) {
				throw new CostException("You' re trying to use more mana then you have. ");
			}
		}
	}

	public int getAvailableMana(Color c) {
		int total = 0;
		if(c == Color.NEUTRAL){
			Set<Color> colors = getColorsInPool();
			for (Color color : colors) {
				List<Mana> pool = getMana(color);
				for (Mana mana : pool) {
					if (!mana.isUsed()) {
						total++;
					}
				}
			}
			return total;
		}
		List<Mana> pool = getMana(c);
		for (Mana mana : pool) {
			if (!mana.isUsed()) {
				total++;
			}
		}
		return total;

	}

}
